package com.dfqy.interceptor;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author oldliu
 * @since 1.0
 */
//@Service("roleInter")
public class RoleInterceptor extends HandlerInterceptorAdapter {
    private RedisTemplate redisTemplate;

    public void setRedisTemplate(RedisTemplate r) {
        this.redisTemplate = r;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null || redisTemplate.opsForValue().get(token) == null) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print("{\"code\":401,\"msg\":\"您还没有登录，不能访问\"}");
            return false;
        }
        //刷新时间
        this.redisTemplate.opsForValue().set(token,redisTemplate.opsForValue().get(token),30, TimeUnit.MINUTES);
        //        if(request.getSession().getAttribute("LOGIN_USER")==null){
//            request.setAttribute("msg","您还没有登录，不能访问"+request.getServletPath());
//           // request.getRequestDispatcher("/login.jsp").forward(request,response);
//           response.setContentType("application/json;charset=utf-8");
//            response.getWriter().print("{\"code\":401,\"msg\":\"您还没有登录，不能访问\"}");
//            return false;
//        }
        return true;
    }
}
